import { forwardRef, useEffect, useImperativeHandle } from 'react';
import { TextArea } from 'antd-mobile';
import { getMessage, TextWidget } from '@inbiz/react';
import { inbiz } from '@inbiz/render';
import { connect, useField, mapProps } from '@formily/react';
import { Field } from '@formily/core';
import { useEvents } from '@inbiz/utils';
import { defaultProps } from '../../designer/schema';
import api from '../web/api';

export type IProps = {
  value: string;
  readOnly: boolean;
  disabled: boolean;
  inbiz: inbiz;
  title: string;
  emit?: () => void;
  callBackEvents?: {
    onBeforeChange?: (v: string) => boolean;
  };
  viewMode?:string;
} & typeof defaultProps;

const EformTextArea = forwardRef((props: IProps, ref: any) => {
  const { inbiz, maxLength, minLength, placeholder,viewMode, ...other } = props;
  const filed = useField<Field>();
  const [configEvents] = useEvents(props.callBackEvents, props.emit);

  useImperativeHandle(
    ref,
    () => ({
      ...api(configEvents, props, filed),
    }),
    [],
  );

  // 自定义验证逻辑
  useEffect(() => {
    const cls = filed.decoratorProps.className.includes('areaWarningMessage')
      ? filed.decoratorProps.className
      : filed.decoratorProps.className + ' areaWarningMessage';
    const cls1 = filed.decoratorProps.className.includes('areaWarningMessage1')
      ? filed.decoratorProps.className
      : filed.decoratorProps.className + ' areaWarningMessage1';
    props.showCount ? cls : cls1;

    filed.setDecoratorProps(filed.decoratorProps);
    filed.setValidatorRule('validator', (value: string, rule: any, ctx: any) => {
      if (ctx.field.componentProps.maxLength && value) {
        if (maxLength && value?.length > maxLength) {
          // return getMessage('EformTextArea.validate.maxLengthNumber') + maxLength;
          return (
            <>
              <TextWidget>EformTextArea.validate.maxLengthNumber</TextWidget>
              {maxLength}
            </>
          );
        }
      }
      return true;
    });
  }, [filed]);

  return viewMode=='look'?<div style={{fontSize:'16px'}}>{props?.value}</div>:<TextArea {...other} placeholder={placeholder} maxLength={maxLength} />;
});

(
  EformTextArea as typeof EformTextArea & IDefaultValueFormat<typeof defaultProps>
).defaultValueFormat = (props: any): string | void => {
  if (props.defaultValue && props.defaultValue.length > 0) {
    return props.defaultValue;
  }
  if (!props.value) {
    return '';
  }
};

export default connect(
  EformTextArea,
  mapProps({}, (props, field) => {
    const { ...others } = props;
    //   field.decoratorProps.addonAfter = props.addonAfter;
    if (!props.maxLength) {
      others.maxLength = undefined;
    }
    if (!props.minLength) {
      others.minLength = undefined;
    }
    others.placeholder = getMessage(props.placeholder);
    return { ...others };
  }),
);
